package com.service.impl;

import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.List;
import java.math.BigDecimal;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.utils.PageUtils;
import com.utils.Query;

import com.dao.KanjiaDao;
import com.entity.KanjiaEntity;
import com.entity.view.KanjiaView;
import com.service.KanjiaService;

@Service("kanjiaService")
public class KanjiaServiceImpl extends ServiceImpl<KanjiaDao, KanjiaEntity> implements KanjiaService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<KanjiaEntity> page = this.selectPage(
                new Query<KanjiaEntity>(params).getPage(),
                new EntityWrapper<KanjiaEntity>()
        );
        return new PageUtils(page);
    }
    
    @Override
    public List<KanjiaView> selectListView(Wrapper<KanjiaEntity> wrapper) {
        return baseMapper.selectListView(wrapper);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Wrapper<KanjiaEntity> wrapper) {
        Page<KanjiaView> page = new Query<KanjiaView>(params).getPage();
        page.setRecords(baseMapper.selectListView(page, wrapper));
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }
    
    @Override
    public String getReferencePrice(String shangpinmingcheng, String wupinfenlei) {
        // 模糊匹配商品名称
        BigDecimal avgPrice = baseMapper.getAvgPriceByCategory(shangpinmingcheng, wupinfenlei);
        
        if (avgPrice != null && avgPrice.compareTo(BigDecimal.ZERO) > 0) {
            return String.format("相似商品近 3 本同款成交均价：%.2f 元", avgPrice.floatValue());
        } else {
            return "暂无相似商品成交记录";
        }
    }
    
    @Override
    public Float calculateKanjiaPrice(String shangpinmingcheng, String wupinfenlei, Float originalPrice) {
        // 获取相似商品的平均价格
        BigDecimal avgPrice = baseMapper.getAvgPriceByCategory(shangpinmingcheng, wupinfenlei);
        
        if (avgPrice != null && avgPrice.compareTo(BigDecimal.ZERO) > 0) {
            // 如果有参考均价，需要判断均价是否低于原价
            Float avgPriceFloat = avgPrice.floatValue();
            if (avgPriceFloat < originalPrice) {
                // 参考均价低于原价，使用均价作为砍价价格（市场价更低，有砍价空间）
                return avgPriceFloat;
            } else {
                // 参考均价高于或等于原价，说明当前价格已经很优惠，使用原价的8折作为砍价价格
                return originalPrice * 0.8f;
            }
        } else {
            // 如果没有参考数据，使用原价的8折作为默认砍价价格
            return originalPrice * 0.8f;
        }
    }
} 